package cn.admin.remoting.serialize.impl;

import cn.admin.remoting.Connection;
import cn.admin.remoting.impl.DefaultConnection;
import cn.admin.remoting.locale.LogResources;
import cn.admin.remoting.util.LoggerInit;
import org.apache.commons.lang.StringUtils;
import org.apache.mina.common.IoSession;

public class RemotingProtocolCodecFilter extends CodecFilterBase {

    @Override
    public void filterClose(NextFilter nextFilter, IoSession session) throws Exception {

        try {
            Connection conn = DefaultConnection.findBySession(session);
            session.setAttribute(Connection.INIT_CLOSE);
            String cause = (String) session.getAttribute(Connection.CLOSE_REASON);
            if (!StringUtils.isBlank(cause) && !"null".equals(cause.trim())) {
                LoggerInit.LOGGER.warn(LogResources.getLog(LogResources.INIT_CLOSE_CONNECTION,conn,cause));
            } else {
                LoggerInit.LOGGER.warn(LogResources.getLog(LogResources.INIT_CLOSE_CONNECTION,
                        conn,cause),new Exception());
            }
        } finally {
            super.filterClose(nextFilter,session);
        }

    }

    @Override
    public void sessionClosed(NextFilter nextFilter, IoSession session) throws Exception {
        try {
            if (null == session.getAttribute(Connection.INIT_CLOSE)) {
                Connection conn = DefaultConnection.findBySession(session);
                LoggerInit.LOGGER.warn(LogResources.getLog(LogResources.NON_INIT_CLOSE_CONNECTION
                        ,conn));
            }
        } finally {
            super.sessionClosed(nextFilter,session);
        }
    }
}
